package com.EWS.service.impl;

import com.EWS.Dao.UserDao;
import com.EWS.Dao.impl.UserDaoImpl;
import com.EWS.model.UserDto;
import com.EWS.service.UserService;
import com.EWS.util.MD5Utils;

import java.util.List;
import java.util.UUID;

public class UserServiceImpl implements UserService {
    private UserDao userDao = new UserDaoImpl();
    @Override
    public int register(UserDto userDto) {
        // 将Servlet传来的注册用户密码进行加密
        String salt = UUID.randomUUID().toString();
        // 替换字符串中所有的 -
        salt = salt.replaceAll("-","");
        userDto.setSalt(salt);
        userDto.setPassWord(MD5Utils.stringToMD5(userDto.getPassWord()+salt));
        // 然后将注册信息传到Dao层与数据库交互，上传到数据库
        return userDao.register(userDto);
    }

    @Override
    public String login(String userName, String passWord) {
        // 将信息传递到Dao与数据库交互返回用户的信息，若返回信息为空则说明用户不存在
        UserDto userDto = userDao.login(userName);
        // 用户信息为空，说明该用户不存在
        if(userDto == null){
            return "NoExist";
        }
        // 用户信息不为空，则判断密码是否正确
        // 在Dao层已经将该用户的用户表信息转化为JavaBean实体类，可用直接用userDto
        String dbPassWord = userDto.getPassWord();
        String salt = userDto.getSalt();
        passWord = MD5Utils.stringToMD5(passWord+salt);
        if(dbPassWord.equals(passWord)){
            return "loginSuccess";
        }
        return "loginFail";
    }

    @Override
    public List<UserDto> getUserStudy(String userName,String word) {
        return userDao.getUserStudy(userName,word);
    }

    @Override
    public int addWord(String userName,String word, String definition) {
        return userDao.addWord(userName,word,definition);
    }

    @Override
    public int updateStudy(String userName, String word) {
        return userDao.updateStudy(userName,word);
    }

    @Override
    public int deleteWord(String userName, String word) {
        return userDao.deleteWord(userName,word);
    }

    @Override
    public int updatePassword(UserDto userDto, String password) {
        return userDao.updatePassword(userDto,password);
    }

    @Override
    public UserDto getUserByName(String userName) {
        return userDao.getUserByName(userName);
    }
}
